<template>
  <div class="createPost-container">
    <el-form
      ref="postForm"
      :model="postForm"
      :rules="rules"
      class="form-container"
      :disabled="isView"
    >
      <div class="createPost-main-container">
        <el-row gutter="80">
          <el-col :span="12">
            <div class="postInfo-container">
              <el-row>
                <el-form-item
                  style="margin-bottom: 40px"
                  prop="machineName"
                  label-width="180px"
                  label="仪器名称："
                >
                  <el-input
                    v-model="postForm.machineName"
                    :maxlength="100"
                    name="name"
                    required
                    placeholder="请输入仪器名称"
                  >
                  </el-input>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item
                  style="margin-bottom: 40px"
                  label-width="180px"
                  label="仪器介绍："
                >
                  <el-input
                    v-model="postForm.machineContent"
                    type="textarea"
                    class=""
                    :autosize="{ minRows: 4, maxRows: 8 }"
                    placeholder="请输入内容"
                  />
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item
                  style="margin-bottom: 40px"
                  prop="machinePhoto"
                  label-width="180px"
                  label="仪器图片："
                >
                  <el-upload
                    class="image-uploader"
                    action="http://localhost:3001/api/machines/upload"
                    :show-file-list="false"
                    :on-preview="handlePreview"
                    :on-success="handleimageSuccess"
                    :before-upload="beforeimageUpload"
                  >
                    <img
                      v-if="postForm.machinePhotoPath"
                      :src="postForm.machinePhotoPath"
                      class="image"
                    />
                    <i v-else class="el-icon-plus image-uploader-icon"
                      >点击上传图片</i
                    >
                  </el-upload>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item
                  style="margin-bottom: 40px"
                  prop="machineStatus"
                  label-width="180px"
                  label="仪器状态："
                >
                  <template>
                    <el-radio v-model="postForm.machineStatus" label="可用"
                      >可用</el-radio
                    >
                    <el-radio v-model="postForm.machineStatus" label="不可用"
                      >不可用</el-radio
                    >
                  </template>
                </el-form-item>
              </el-row>
            </div>
          </el-col>

          <el-col :span="12">
            <el-row>
              <el-form-item label-width="180px" label="仪器:" prop="id">
                <el-select
                  v-model="postForm.machineOwnerId"
                  :remote-method="getUserList"
                  filterable
                  remote
                  placeholder="请选择联系人"
                  :loading="loading"
                  @change="changeUser"
                >
                  <el-option
                    v-for="item in userListOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item
                style="margin-bottom: 40px"
                prop="machineOwnerPhone"
                label-width="180px"
                label="电话号码："
              >
                <el-input
                  v-model="postForm.machineOwnerPhone"
                  :maxlength="100"
                  name="name"
                  :disabled="true"
                >
                </el-input>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item
                style="margin-bottom: 40px"
                prop="machineOwnerEmail"
                label-width="180px"
                label="邮箱："
              >
                <el-input
                  v-model="postForm.machineOwnerEmail"
                  :maxlength="100"
                  name="name"
                  required
                  :disabled="true"
                >
                </el-input>
              </el-form-item>
            </el-row>
          </el-col>
        </el-row>
      </div>

      <el-button
        v-show="!isView"
        v-loading="loading"
        style="margin-left: 230px; width: 100px"
        type="success"
        @click="submitForm"
      >
        保存
      </el-button>
    </el-form>
    <el-button
        v-show="isView"
        v-loading="loading"
        style="margin-left: 230px; width: 100px"
        type="success"
        @click="$router.push(`/machineappointment/create`)"
      >
        预约
    </el-button>
  </div>
</template>

<script>
import { fetchUserList } from "@/api/user";
import { fetchMachineById, createMachine, updateMachine } from "@/api/machine";
const defaultForm = {
  machineName: "", // 仪器名称
  machineContent: "", // 仪器介绍
  machinePhotoPath: "", // 仪器图片
  machineOwnerId: "", // 仪器联系人ID
  machineOwnerName: "", // 仪器联系人名字
  machineOwnerPhone: "", // 仪器联系人电话
  machineOwnerEmail: "", // 仪器联系人邮箱
  machineStatus: "可用", // 仪器状态： 可用，不可用
  id: undefined,
};

export default {
  name: "MachineDetail",
  props: {
    isEdit: {
      type: Boolean,
      default: false,
    },
    isView: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("此为必填项"));
      } else {
        callback();
      }
    };

    return {
      postForm: Object.assign({}, defaultForm),
      loading: false,
      userList: [],
      userListOptions: [],
      rules: {
        machineName: [{ required: true, validator: validateRequire }],
        machineOwnerId: [{ required: true, validator: validateRequire }],
        machineOwnerEmail: [{ required: true, validator: validateRequire }],
        machineStatus: [{ required: true, validator: validateRequire }],
      },
    };
  },
  created() {
    this.getUsers();
    if (this.isEdit || this.isView) {
      const id = this.$route.params && this.$route.params.id;
      this.fetchData(id);
    }
  },
  methods: {
    handlePreview(file) {
      let a = document.createElement('a');
      let event = new MouseEvent('click');
      a.download = file.name;
      a.href = file.response? `http://localhost:3001/${file.response.srcurl}` : file.url;
      a.dispatchEvent(event);
      console.log(file);
    },
    getUsers() {
      this.listLoading = true;
      fetchUserList().then((res) => {
        this.userList = res.data.map((item) => {
          return {
            label: item.userName,
            value: item.id,
            phone: item.userCellphone,
            email: item.userEmail,
          };
        });

        this.userListOptions = this.userList;

        this.listLoading = false;
      });
    },
    getUserList(query) {
      if (query !== "") {
        this.loading = true;
        this.userListOptions = userList.filter((item) => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
        this.loading = false;
      } else {
        this.userListOptions = userList;
      }
    },
    changeUser(val) {
      const selectedItem = this.userList.find((item) => {
        return item.value === val;
      });
      this.postForm.machineOwnerName = selectedItem.label;
      this.postForm.machineOwnerPhone = selectedItem.phone;
      this.postForm.machineOwnerEmail = selectedItem.email;
    },
    fetchData(id) {
      fetchMachineById(id)
        .then((res) => {
          this.postForm = res.data[0];
        })
        .catch((err) => {
          console.log(err);
        });
    },
    async handleimageSuccess(res, file) {
      if (res.status === "1") return this.$message.error(res.message);
      this.postForm.machinePhotoPath = `http://localhost:3001/${res.srcurl}`;
    },
    beforeimageUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 5;

      if (!isJPG) {
        this.$message.error("image picture must be JPG format!");
      }
      if (!isLt2M) {
        this.$message.error("image picture size can not exceed 5MB!");
      }
      return isJPG && isLt2M;
    },
    submitForm() {
      console.log(this.postForm);
      this.$refs.postForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.postForm.id) {
            updateMachine(this.postForm.id, this.postForm)
              .then((res) => {
                if (res.data) {
                  this.$router.push("/machine/list");
                  this.$message({
                    title: "成功",
                    message: "仪器信息更新成功",
                    type: "success",
                    duration: 2000,
                  });
                } else {
                  this.$message({
                    message: "仪器信息更新失败",
                    type: "error",
                  });
                }
                this.loading = false;
              })
              .catch((err) => {
                this.loading = false;
              });
          } else {
            createMachine(this.postForm)
              .then((res) => {
                if (res.data) {
                  this.$router.push("/machine/list");

                  this.$message({
                    title: "成功",
                    message: "仪器创建成功",
                    type: "success",
                    duration: 2000,
                  });
                } else {
                  this.$message({
                    message: "仪器创建失败",
                    type: "error",
                  });
                }
                this.loading = false;
              })
              .catch((err) => {
                this.loading = false;
              });
          }
        } else {
          console.log("仪器信息保存失败");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .image-uploader .el-upload {
    border: 1px dashed #d9d9d9 !important;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .image-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .image-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .image {
    width: 178px;
    height: 178px;
    display: block;
  }

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }
}

.identity-container {
  margin-top: 50px;
}
</style>
